﻿using BoilerplateWPF.Models;
using BoilerplateWPF.Services.Interfaces;
using BoilerplateWPF.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace BoilerplateWPF.ViewModels
{
    internal class LoginViewModel : ObservableObject
    {
        public delegate void LoginSuccessfuler(UserModel user);
        public event LoginSuccessfuler LoginSuccessful;

        private UserModel _currentUser;
        private readonly IUserService _userService;
        private bool _isCheck1; // 员工
        private bool _isCheck2; // 管理员
        private bool _isLoading; // 登录中
        private string _tipMessage; // 提示

        public string UserAccount
        {
            get => _currentUser.UserAccount;
            set { _currentUser.UserAccount = value; RaisePropertyChanged(); }
        }
        public string Password
        {
            get => _currentUser.UserPassword;
            set { _currentUser.UserPassword = value; RaisePropertyChanged(); }
        }
        public int IdentityID
        {
            get => _currentUser.IdentityID;
            set
            {
                _currentUser.IdentityID = value;
                RaisePropertyChanged();
                RaisePropertyChanged(nameof(RankName)); // 重要：通知RankName更新
            }
        }
        public string RankName => _currentUser.RankName;
        public bool IsCheck1
        {
            get => _isCheck1;
            set
            {
                if (SetProperty(ref _isCheck1, value) && value)
                {
                    IsCheck2 = false; // 互斥选择
                    IdentityID = 1;  // 员工
                }
            }
        }
        public bool IsCheck2
        {
            get => _isCheck2;
            set
            {
                if (SetProperty(ref _isCheck2, value) && value)
                {
                    IsCheck1 = false; // 互斥选择
                    IdentityID = 2;  // 管理员
                }
            }
        }
        public bool IsLoading
        {
            get => _isLoading;
            set => SetProperty(ref _isLoading, value);
        }
        public string TipMessage
        {
            get => _tipMessage;
            set => SetProperty(ref _tipMessage, value);
        }
        
        public ICommand LoginCommand { get; }
        public ICommand ExitCommand { get; }

        public LoginViewModel()
        {
            // 内部创建空Model
            _currentUser = new UserModel();
            // 直接从静态属性获取服务
            _userService = ServiceLocator.UserService;
            // 初始化命令对象
            LoginCommand = new RelayCommand(ExecuteLogin, CanExecuteLogin);
            ExitCommand = new RelayCommand(ExecuteExit);
            // 设置默认值
            TipMessage = null;
            // 事件订阅和初始化
        }

        private bool CanExecuteLogin(object obj)
        {
            return !IsLoading; // 不在加载过程中
        }

        private void ExecuteLogin(object obj)
        {
            // 添加调试输出
            //Debug.WriteLine("--------------------------------------------------");
            //Debug.WriteLine($"输入的用户名: {UserAccount}");
            //Debug.WriteLine($"输入的密码: {Password}");
            //Debug.WriteLine($"IsCheck1: {IsCheck1}, IsCheck2: {IsCheck2}");
            //Debug.WriteLine("--------------------------------------------------");

            // 先进行客户端验证
            if (string.IsNullOrEmpty(UserAccount))
            {
                TipMessage = "请输入用户名";
                return;
            }
            if (string.IsNullOrEmpty(Password))
            {
                TipMessage = "请输入密码";
                return;
            }
            // 验证用户是否选择了身份（基于UI控件状态）也可以考虑判断 IdentityID 的值 各有利弊
            if (!(IsCheck1 || IsCheck2))
            {
                TipMessage = "请选择身份";
                return;
            }

            IsLoading = true; // 开始加载，禁用按钮
            TipMessage = "加载中";

            try
            {
                UserModel result = _userService.ValidateUserLogin(UserAccount, Password, IdentityID);
                if (result != null)
                {
                    Debug.WriteLine("--------------------------------------------------");
                    Debug.WriteLine($"用户名: {result.UserAccount}");
                    Debug.WriteLine($"昵称: {result.UserName}");
                    Debug.WriteLine($"密码: {result.UserPassword}");
                    Debug.WriteLine($"IdentityID: {result.IdentityID}");
                    Debug.WriteLine($"身份信息: {result.RankName}"); // 计算属性
                    Debug.WriteLine("--------------------------------------------------");

                    //LoginSuccessful?.Invoke(_currentUser); // 只是个容器 不包含UserName等
                    LoginSuccessful?.Invoke(result);
                }
                else
                {
                    TipMessage = "用户名、密码或身份信息不正确";
                }
            }
            catch (Exception ex)
            {
                TipMessage = "登录过程中发生未知错误\r\n请联系管理员";
                Console.WriteLine("|登录功能报错|，错误为：" + ex);
            }
            finally
            {
                IsLoading = false; // 结束加载，重新启用按钮
            }
        }

        private void ExecuteExit(object obj)
        {
            //Environment.Exit(0); // 暴力关闭
            Application.Current.Shutdown();
        }
    }
}
